from models.engine import db

class SystemAreaCode(db.Model):
    __tablename__ = 'sys_area_code'
    __table_args__ = (
        db.PrimaryKeyConstraint('code', name='sys_area_code_pkey'),
        db.Index('sys_area_code_code_idx', 'code')
    )

    code = db.Column(db.BigInteger(), nullable=False)
    name = db.Column(db.String(100), nullable=False)
    parent_code = db.Column(db.BigInteger(), nullable=True)
    area_type = db.Column(db.SmallInteger, nullable=False)
    name_path = db.Column(db.String(255), nullable=True)
    code_path = db.Column(db.String(255), nullable=True)

    @property
    def postal_code(self)->str:
        return str(self.code*(1/1000000))
    
    @staticmethod
    def from_postal(val:str)->int:
        if val:
            try:
                i_val = int(val)
                return i_val * 1000000
            except:
                pass
        return -1

    @property
    def distrct_str(self)->str:
        if self.name_path is None:
            return ''
        parts = self.name_path.split('>')
        result = '>'.join([x for i, x in enumerate(parts) if x not in parts[:i]])
        return result.replace('>','/')